package com.clippick;

import java.util.Map;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import co.kr.clippick.R;

import com.clippick.api.GetApi;
import com.clippick.common.GlobalValue;
import com.clippick.common.Toasts;
import com.clippick.common.Utils;

public class NewJoinActivity extends Activity {

	private Context mContext;
	private ConnectivityManager manager;
	private Button joinButton, facebookButton, backButton;
	private LinearLayout backButtonLayer;
	private EditText passwordEditText, rePasswordEditText, emailEditText;
	private ProgressDialog mProgress = null;

	private String userEmail = "";
	private String userPassword = "";
	private String userRePassword = "";

	final static int AUTHORIZE_ACTIVITY_RESULT_CODE = 0;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_join);
		mContext = this;

		manager = (ConnectivityManager) mContext
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		emailEditText = (EditText) findViewById(R.id.email);
		passwordEditText = (EditText) findViewById(R.id.password);
		rePasswordEditText = (EditText) findViewById(R.id.re_password);

		rePasswordEditText
				.setOnEditorActionListener(new TextView.OnEditorActionListener() {
					@Override
					public boolean onEditorAction(TextView v, int actionId,
							KeyEvent event) {
						if (actionId == EditorInfo.IME_ACTION_GO) {
							userEmail = emailEditText.getText().toString();
							userPassword = passwordEditText.getText()
									.toString();
							userRePassword = rePasswordEditText.getText()
									.toString();

							validateSignUpUserInfo(userEmail, userPassword,
									userRePassword);
						}

						return true;
					}
				});

		joinButton = (Button) findViewById(R.id.join_button);
		joinButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				userEmail = emailEditText.getText().toString();
				userPassword = passwordEditText.getText().toString();
				userRePassword = rePasswordEditText.getText().toString();

				validateSignUpUserInfo(userEmail, userPassword, userRePassword);

			}
		});

		facebookButton = (Button) findViewById(R.id.facebook);
		facebookButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(mContext, NewLoginActivity.class);
				intent.putExtra("facebook", true);
				startActivity(intent);
				finish();
			}
		});

		backButton = (Button) findViewById(R.id.back);
		backButtonLayer = (LinearLayout) findViewById(R.id.back_button_layer);

		backButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		backButtonLayer.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	private void validateSignUpUserInfo(String email, String pass, String rePass) {
		if (Utils.checkEmail(userEmail)) {
			if (userPassword.equals(userRePassword)) {
				if (Utils.checkNetwokState(manager)) {
					new SignUpTask().execute();
				} else {
					// network error
					Toasts.showToast(mContext, getString(R.string.network_fail));
				}
			} else {
				// password error
				Toasts.showToast(mContext,
						getString(R.string.signup_wrong_password));
			}
		} else {
			// email error
			Toasts.showToast(mContext, getString(R.string.signup_wrong_email));
		}
	}

	private void hideKeyboard(EditText editText) {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
	}

	class SignUpTask extends AsyncTask<String, String, String> {
		String response = "";

		protected void onPreExecute() {
			hideKeyboard(emailEditText);
			hideKeyboard(rePasswordEditText);
			hideKeyboard(passwordEditText);

			emailEditText.setEnabled(false);
			rePasswordEditText.setEnabled(false);
			passwordEditText.setEnabled(false);

			mProgress = new ProgressDialog(mContext);
			mProgress.setMessage("Loading...");
			mProgress.setCancelable(false);
			mProgress.show();
		}

		@Override
		protected String doInBackground(String... params) {
			GetApi api = new GetApi(mContext);
			response = api.signUpWithoutName(userEmail, userPassword);
			return null;
		}

		protected void onPostExecute(String unused) {
			if (response.equals("success")) {
				new LoginTask().execute();
			} else {
				mProgress.dismiss();

				emailEditText.setEnabled(true);
				rePasswordEditText.setEnabled(true);
				passwordEditText.setEnabled(true);

				/*
				 * 1. Wrong or Empty Params 2. Invalid Email Address 3. Email
				 * Exists 4. Email not deliverable
				 */
				Toasts.showToast(mContext, response);
			}
		}
	}

	class LoginTask extends AsyncTask<String, String, String> {
		int returnCode = 0;
		String returnMessage = null;
		Map<String, String> response = null;

		protected void onPreExecute() {
			// hideKeyboard(emailEditText);
			// hideKeyboard(passwordEditText);
		}

		@Override
		protected String doInBackground(String... params) {
			GetApi api = new GetApi(mContext);
			response = api.loginApi(userEmail, userPassword);
			returnCode = Integer.parseInt(response.get("returnCode"));

			if (returnCode != 200) {
				returnMessage = response.get("returnMessage");
			}

			return null;
		}

		protected void onPostExecute(String unused) {
			mProgress.dismiss();

			switch (returnCode) {
			case 200:
				// store user data
				GlobalValue.storeUserEmail(mContext, userEmail);
				GlobalValue.storeUserPassword(mContext, userPassword);
				GlobalValue.setFbUser(mContext, true);
				GlobalValue.setAutoSync(mContext, true);
				GlobalValue.setMaxStarValue(mContext,
						Integer.parseInt(response.get("MaxStar").toString()));
				GlobalValue.setStarCountValue(mContext,
						Integer.parseInt(response.get("UsedStar").toString()));

				GlobalValue.USER_KEY = response.get("REGISTRATION_KEY")
						.toString();
				GlobalValue.AppLatestSyncTime = GlobalValue.UPDATE_TIME;
				GlobalValue.IS_FIRST_LOGIN_USER = true;

				// store as global variable to access easier
				GlobalValue.USER_ID = userEmail;
				GlobalValue.USER_KEY = GlobalValue
						.getUserRegistrationKey(mContext);
				GlobalValue.UPDATE_TIME = response.get("UPDATE_TIME")
						.toString();
				GlobalValue.AppLatestSyncTime = GlobalValue.UPDATE_TIME;
				GlobalValue.IS_FIRST_LOGIN_USER = true;

				Intent intent = new Intent(mContext, NewMainActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);

				Intent updateViewIntent = new Intent();
				updateViewIntent.setAction("com.new.clippick.FinishIntro");
				sendBroadcast(updateViewIntent);

				Toasts.showToast(mContext, getString(R.string.signup_success));

				finish();

				break;

			default:
				// show message why failed logging in
				Toasts.showToast(mContext, returnMessage);
				break;
			}
		}
	}
}
